package cn.wolfcode.rbac.springSecurity.config;

import cn.wolfcode.rbac.springSecurity.detail.MyUserDetailsService;
import cn.wolfcode.rbac.springSecurity.filter.JwtAuthenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

//    @Autowired
//    private CorsFilter corsFilter;

    @Autowired
    private JwtAuthenFilter jwtAuthenFilter;

    /**
     * 配置拦截规则
     * @param http the {@link HttpSecurity} to modify
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用csrf
        http.csrf().disable();

        //配置拦截规则
        http.authorizeRequests()
                .antMatchers("/api/code","/api/login","/api/logout").permitAll()
                .antMatchers("/**").authenticated();

        //配置filter的执行顺序
        //corsFilter -> 自定义filter把用户存入上下文 -> 资源拦截filter
        http.addFilterBefore(jwtAuthenFilter, UsernamePasswordAuthenticationFilter.class);
//        http.addFilterBefore(corsFilter,JwtAuthenFilter.class);
    }

    /**
     * 实例化认证器
     */
    @Bean   //把认证器交给Spring管理，在service层可以依赖注入该对象
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 密码匹配器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    /**
     * 配置认证器 的 数据源 和 密码匹配器
     * @param auth the {@link AuthenticationManagerBuilder} to use
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(myUserDetailsService)  //配置数据源
                    .passwordEncoder(passwordEncoder()); //密码匹配器
    }
}
